<style lang="less">
</style>

<template>
    <div class="device-list-view">
        <Card>
            <span slot="title">设备列表</span>
            <span slot="extra">
                <Button v-if="hasAddBtn" @click.prevent="add" size="small" type="success" >
                    <Icon type="plus"></Icon>添加设备
                </Button>
                <Button size="small" type="success" @click="getDeviceList"><Icon type="loop"></Icon>刷新列表</Button>
            </span>

            <Form label-position="left" label-width="80" inline>
                <Row>
                    <AgentSelect size="small" :agent-id.sync="search.parent_agent_id" @on-change="agentSelectChange"></AgentSelect>
                    <FormItem label="设备状态：">
                        <Select size="small" v-model="search.status" placeholder="设备状态">
                            <Option value="">全部</Option>
                            <Option value="online">在线</Option>
                            <Option value="offline">离线</Option>
                            <Option value="fault">故障</Option>
                        </Select>
                    </FormItem>
                    <FormItem label-width="0">
                        <Button type="success" :loading="searchLoading" size="small" icon="ios-search" @click="handleSearch" >检索</Button>
                        <Button type="warning" :loading="exportLoading" size="small" icon="ios-export" @click="handleExport" >导出二维码 [第{{ page.current }}页]</Button>
                    </FormItem>
                </Row>
                <Row>
                    <FormItem label="添加日期:">
                        <DatePicker size="small" @on-change="handleChangeDate" type="datetimerange" placeholder="请选择时间段" style="width:260px"></DatePicker>
                    </FormItem>
                    <FormItem label="省市区：">
                        <Cascader style="margin-top:5px; width: 250px;" :data="regions" size="small" trigger="hover" v-model="regionSelected"></Cascader>
                    </FormItem>
                    <FormItem label-width="0">
                        <Input style="width: 250px;" size="small" placeholder="设备编号/代理商/设备名称/详细地址" v-model="search.keyword"></Input>
                    </FormItem>
                </Row>
            </Form>
            <Row>
                <Col>
                <Table border :loading="loading" height="450" :context="self" :columns="columns" :data="data"></Table>
                </Col>
            </Row>
            <Row style="padding: 5px 0">
                <Col>
                <Page ref="Page"
                      :total="page.total"
                      :size="page.size"
                      :current.sync="page.current"
                      @on-change="handleChangePage"
                      @on-page-size-change="handleChangePageSize"
                      :page-size-opts="page.sizes" show-sizer show-elevator></Page>
                </Col>
            </Row>
        </Card>

        <Modal v-model="qrCodeModal">
            <p slot="header">设备二维码</p>
            <div style="text-align: center;width: 100%;">
                <img :src="qrcodeImg" alt="">
            </div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import AgentSelect from '../public/AgentSelect.vue';

    const viewButton = (vm, h, row, index) => {
        return h('a', {
                style: {
                    margin: '5px',
                },
                on: {
                    'click': (event) => {
                        vm.showQrcode(row)
                    }
                }
            }, '查看二维码'
        );
    };

    const editButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.edit(row, index)
                }
            }
        }, '编辑');
    };

    export default {
        components: {
            AgentSelect
        },

        data () {
            return {
                self: this,
                hasAddBtn: false,
                hasToggleStatusBtn: false,

                loading: false,

                page: {
                    total: 0,
                    current: 1,
                    size: 10,
                    sizes: [10, 30, 50, 100],
                },

                regions: [],
                regionSelected: [],
                regionLoading: false,

                searchLoading: false,
                exportLoading: false,
                search: {
                    parent_agent_id: '',
                    keyword: '',
                    created_at: '',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    status: '',
                    is_export: 'no',
                },

                qrcodeImg: '',
                qrCodeModal: false,

                columns: [
                    {
                        title: '设备编号',
                        key: 'device_sn',
                        fixed: 'left',
                        width: 220
                    },
                    {
                        title: '设备名称',
                        key: 'name',
                        fixed: 'left',
                        width: 120
                    },
                    {
                        title: '设备状态',
                        key: 'status_text',
                        width: 120
                    },
                    {
                        title: '阶梯定价',
                        key: 'ladder_price',
                        width: 150
                    },
                    {
                        title: '插口状态',
                        key: 'ports',
                        width: 280
                    },
                    {
                        title: '所属代理',
                        key: 'agent_name',
                        width: 120
                    },
                    {
                        title: '地址',
                        key: 'full_address',
                        width: 250
                    },
                    {
                        title: '备注',
                        key: 'remark',
                        align: 'center',
                        width: 220
                    },
                    {
                        title: '添加日期',
                        key: 'created_at',
                        width: 220
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 150
                    }

                ],
                data: []
            }
        },

        watch: {
            regionSelected: function (newVal) {
                this.search.province_code = newVal[0];
                this.search.city_code = newVal[1];
                this.search.district_code = newVal[2];
            }
        },

        mounted () {
            this.getDeviceList();
            this.getRegions();
        },

        created () {
            this.init();
            this.checkHasActionRole();
        },

        methods: {
            checkHasActionRole ()  {
                let userRoles = this.$store.state.user.user.roles_name || [];
                if (util.oneOf('agent', userRoles) && this.$store.state.user.user.extension.agent_level == 3) {
                    this.hasAddBtn = true;
                } else {
                    this.hasAddBtn = false;
                }
            },

            handleChangeDate (date) {
                if (date) {
                    this.search.created_at = date;
                } else {
                    this.search.created_at = [];
                }
            },

            init () {
                let vm = this;

                this.columns.forEach(item => {
                    const portStatus = (h, status) => {
                        return h('span', {
                            style: {
                                color: status ? 'red' : 'green'
                            }
                        }, status ? '开启' : '闲置');
                    };

                    if (item.key == 'ports') {
                        item.render = (h, param) => {
                            const ports = [];

                            ports.push(h('div', {}, [
                                [h('span', {}, '插口1：'), portStatus(h, param.row.ports.p1)],
                                [h('span', {}, '; 插口2：'), portStatus(h, param.row.ports.p2)],
                                [h('span', {}, '; 插口3：'), portStatus(h, param.row.ports.p3)]
                            ]));

                            ports.push(h('div', {}, [
                                [h('span', {}, '插口4：'), portStatus(h, param.row.ports.p4)],
                                [h('span', {}, '; 插口5：'), portStatus(h, param.row.ports.p5)],
                                [h('span', {}, '; 插口6：'), portStatus(h, param.row.ports.p6)]
                            ]));

                            return ports;
                        };
                    }

                    if (item.key == 'ladder_price') {
                        item.render = (h, param) => {
                            const ports = [];

                            ports.push(h('div', {}, `${param.row.ladder_price.one.min} ~ ${param.row.ladder_price.one.max}分钟：${param.row.ladder_price.one.price}元`));
                            ports.push(h('div', {}, `${param.row.ladder_price.two.min} ~ ${param.row.ladder_price.two.max}分钟：${param.row.ladder_price.two.price}元`));
                            ports.push(h('div', {}, `${param.row.ladder_price.three.min} ~ ${param.row.ladder_price.three.max}分钟：${param.row.ladder_price.three.price}元`));
                            ports.push(h('div', {}, `${param.row.ladder_price.four.min}分钟之后：${param.row.ladder_price.four.price}元`));

                            return ports;
                        };
                    }

                    if (item.key == 'action') {
                        item.render = (h, param) => {
                            const buttons = [];
                            buttons.push(viewButton(vm, h, param.row, param.index));

                            let userRoles = this.$store.state.user.user.roles_name || [];
                            if (util.oneOf('agent', userRoles) && this.$store.state.user.user.extension.agent_level == 3) {
                                buttons.push(editButton(vm, h, param.row, param.index));
                            }

                            return buttons;
                        };
                    }
                });
            },

            getDeviceList () {
                this.loading = true;
                this.searchLoading = true;

                let params = {
                    page: this.page.current,
                };
                params = Object.assign(params, this.search);

                util.api().get(`/admin/api/devices`, {
                    params,
                    headers: {
                        pageSize: this.page.size,
                    }
                }).then((resp) => {
                    this.$Message.destroy();
                    if (resp.data.status == true) {
                        this.data = resp.data.data;
                        this.page.total = resp.data.meta.total;
                        this.page.current = resp.data.meta.current_page;
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                    this.loading = false;
                    this.searchLoading = false;
                }).catch((e) => {
                    util.handleApiException(e, this, '获取设备列表失败');
                    this.searchLoading = false;
                })
            },

            handleExport () {
                this.exportLoading = true;
                this.search.is_export = 'yes';

                let params = {
                    page: this.page.current,
                };
                params = Object.assign(params, this.search);

                util.api().get(`/admin/api/devices`, {
                    params,
                    headers: {
                        pageSize: this.page.size,
                    }
                }).then((resp) => {
                    if (resp.data.status == false) {
                        this.$Notice.error({ title: '导出失败' });
                    } else {
                        this.$Notice.success({ title: '导出成功', desc: '数据文件下载中...' });
                        window.location.href = resp.data.data.url;
                    }
                    console.log(resp.data);
                    this.search.is_export = 'no';
                    this.exportLoading = false;
                }).catch((e) => {
                    util.handleApiException(e, this, '导出二维码失败');
                    this.search.is_export = 'no';
                    this.exportLoading = false;
                })
            },

            handleSearch () {
                this.page.current = 1;
                this.getDeviceList();
            },

            handleChangePage (page) {
                this.page.current = page;
                this.getDeviceList();
            },

            handleChangePageSize (size) {
                this.page.size = size;
                this.getDeviceList();
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            },

            edit (row, index) {
                this.$router.push({
                    name: 'system-device-edit',
                    query: {
                        id: row.id
                    }
                })
            },

            add () {
                this.$router.push({
                    name: 'system-device-add',
                })
            },

            showQrcode(row) {
                this.qrCodeModal = true;
                this.qrcodeImg = row.qrcode_base64;
                console.log(row)
            },

            agentSelectChange (value) {
                console.log(value);
                this.search.parent_agent_id = value;
            }
        }
    };
</script>
